package com.loongtech.bi.action.system;

import com.loongtech.bi.action.BaseBiSearchAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 持续部署Action
 * @author M
 * @date 2015年2月26日
 */
@Controller("cidAction")
@Scope("view")
public class CidAction extends BaseBiSearchAction{
	private static final long serialVersionUID = 1L;
	
	@Autowired
    private HttpServletRequest request;

    private String result;

	@PostConstruct
	private void init() {
        result = null;

        System.out.println("开始执行集成部署");

        String path = request.getSession().getServletContext().getRealPath("/");
        String shell = path.split("webapps/ROOT/")[0] + "bin/deployCID.sh";
        System.out.println(shell);


        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec(shell.trim());
        } catch (Exception ex) {
            ex.printStackTrace();
            result = "执行脚本异常";
            System.out.println("执行脚本异常");;
        }
        // 返回结果
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line).append("\r\n");
            int retVal = proc.waitFor();
            if (retVal == 0) {
                result = "执行脚本完成：" + sb.toString();
                System.out.println("执行脚本完成：" + sb.toString());
            } else {
                result = "执行脚本异常：" +  retVal;
                System.out.println("执行脚本异常：" +  retVal);;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            result = "执行脚本异常";
            System.out.println("执行脚本异常");;
        }
    }

    public static void main(String[] args) {
        String s = "/usr/local/biroot-tomcat-7.0.64/webapps/ROOT/";
        String[] ss = s.split("webapps/ROOT/");
        System.out.println(ss[0] + "bin/deployCID.sh");
    }

    public String cid() {
        return result;
    }

    @Override
    public void search() {

    }

    @Override
    protected String csvContent() {
        return null;
    }

    @Override
    protected String csvFileName() {
        return null;
    }
}
